package com.xiaohe66.web.infrastructure.mybatis.birth.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaohe66.common.value.Paging;
import com.xiaohe66.web.domain.account.value.AccountId;
import com.xiaohe66.web.domain.birth.agg.Birthday;
import com.xiaohe66.web.domain.birth.repository.BirthdayRepository;
import com.xiaohe66.web.domain.birth.value.BirthdayId;
import com.xiaohe66.web.domain.birth.value.BirthdayValue;
import com.xiaohe66.web.infrastructure.mybatis.birth.convert.BirthdayDoConverter;
import com.xiaohe66.web.infrastructure.mybatis.birth.mapper.BirthdayMapper;
import com.xiaohe66.web.infrastructure.mybatis.birth.model.BirthdayDo;
import com.xiaohe66.web.integration.AbstractMybatisService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import java.time.LocalDate;
import java.util.List;

/**
 * @author xiaohe
 * @since 2023-07-12 15:41
 */
@Repository
@Slf4j
@RequiredArgsConstructor
public class BirthdayRepositoryImpl
        extends AbstractMybatisService<BirthdayDoConverter, BirthdayMapper, BirthdayDo, Birthday, BirthdayId>
        implements BirthdayRepository {

    @Override
    public List<Birthday> list(AccountId createId, Paging paging) {

        LambdaQueryWrapper<BirthdayDo> queryWrapper = new LambdaQueryWrapper<BirthdayDo>()
                .eq(BirthdayDo::getCreateId, createId.getValue())
                .orderByAsc(BirthdayDo::getNextBirthday)
                .orderByDesc(BirthdayDo::getId)
                .last(paging.toLimit());

        List<BirthdayDo> doList = list(queryWrapper);

        return dataConverter.toAgg(doList);
    }

    @Override
    public List<Birthday> listAfterDay(AccountId createId, int day) {

        LocalDate localDate = LocalDate.now().plusDays(day);

        BirthdayDo query = new BirthdayDo();
        query.setCreateId(createId.getValue());
        query.setNextBirthday(localDate);

        List<BirthdayDo> aggList = list(new QueryWrapper<>(query));

        return dataConverter.toAgg(aggList);
    }

    @Override
    public void updateNextBirth() {

        // 更新过去7天内的所有生日
        LocalDate localDate = LocalDate.now().minusDays(7);

        LambdaQueryWrapper<BirthdayDo> queryWrapper = new LambdaQueryWrapper<BirthdayDo>()
                .gt(BirthdayDo::getNextBirthday, localDate)
                .eq(BirthdayDo::getDeleted, false);

        List<BirthdayDo> list = list(queryWrapper);

        for (BirthdayDo birthdayDo : list) {

            Birthday birthday = dataConverter.toAgg(birthdayDo);
            BirthdayValue birthdayValue = birthday.toBirthdayValue();

            LocalDate nextBirthday = birthdayValue.nextBirthday().toDate();

            birthdayDo.setNextBirthday(nextBirthday);

            updateById(birthdayDo);
        }
    }
}
